import React, { useEffect, useMemo, useRef, useState } from 'react';
import { router, Text, Image, View, ScrollView, publishDps, showToast, Button } from '@ray-js/ray';
import { Card } from '@/components/card';
import { IconFont } from '@/components';
import Strings from '@/i18n';
import { CellGroup, Cell, ActionSheet, Switch, Picker, DateTimePicker } from '@ray-js/smart-ui';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { useAppConfig } from '@/hooks/useAppConfig';
import { NavBarCustom } from '@/components/NavBarCustom';
import { InfoCom } from '@/components/info-com';
import res from '@/res/image';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
// @ts-ignore
import { BotBar } from '@/components/bot-bar';
import { useThrottleFn } from 'ahooks';
import { decodeDisinfect, decodeDisturb, encodeDisturb } from '@/utils/parse';

import styles from './index.module.less';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;
const zeroCol = ['00'];

const getTimeMeasureUtils = (time: {
  hour: number;
  minute: number;
  duration?: number;
  status?: boolean;
}) => {
  if (time.hour === undefined) {
    return '';
  }

  const { hour, minute } = time;

  return `${hour < 10 ? `0${hour}` : hour}:${minute < 10 ? `0${minute}` : minute}`;
};

export function Home() {
  const {
    status,
    light,
    auto_clean: autoClean,
    uv_onoff_time: uvOnOffTime, // 杀菌
    filter_reset: filterReset, // 除臭
    sleep_onoff_time: sleepOnOffTime, // 勿扰
    child_lock: childLock, // 儿童锁
    filter_days: filterDays, // 除臭天数
    delay_clean_time: delayCleanTime, // 延时清理时间
  } = useProps();

  const sleepTime = decodeDisturb(sleepOnOffTime);

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const [doubleCheck, setDoubleCheck] = useState({
    show: false,
    title: '',
    tips: '',
    onConfirmCallBack: () => {},
  });

  const [cleanTimeShow, setCleanTimeShow] = useState(false);

  const [sleepOption, setSleepOption] = useState({
    show: false,
    status: 'list',
  });

  const [sleepTimeConfig, setSleepTimeConfig] = useState(sleepTime);
  console.log(`🚀 ~ sleepTimeConfig:`, sleepTimeConfig);

  const columns = [
    {
      values: new Array(11).fill(1).map((x, i) => (i < 10 ? `0${i}` : `${i}`)),
      style: { flex: 'none', width: 'auto', minWidth: '91px' },
      fontStyle: { fontSize: '16px' },
      unit: 'min',
      defaultIndex: Math.floor(delayCleanTime / 60),
    },
    {
      values: new Array(60).fill(1).map((x, i) => (i < 10 ? `0${i}` : `${i}`)),
      style: { flex: 'none', width: 'auto', minWidth: '91px' },
      unit: 'sec',
      defaultIndex: delayCleanTime % 60,
    },
  ];

  const delayCleanTimeRef = useRef(0);

  useEffect(() => {
    delayCleanTimeRef.current = delayCleanTime;
  }, [delayCleanTime]);

  const sleepTimeConfigRef = useRef(sleepTimeConfig);

  useMemo(() => {
    setSleepTimeConfig(sleepTime);
    sleepTimeConfigRef.current = sleepTime;
  }, [JSON.stringify(sleepTime)]);

  const renderSchedule = () => {
    return (
      <View className={styles.scheduleContainer}>
        <View
          className={styles.schedule}
          onClick={() => {
            handleJump('cleanSchedule');
          }}
        >
          <Image src={res.time} className={styles.scheduleIcon} />
          <Text className={styles.scheduleText}>{Strings.getLang('schedule')}</Text>
        </View>
      </View>
    );
  };

  const renderLogo = () => {
    return (
      <View className={styles.logoContainer}>
        <Text className={styles.statusText}> {Strings.getLang(status)}</Text>
        <Image src={res.logo} className={styles.logo} />

        <Image
          src={light ? res.lightOn : res.lightOff}
          className={styles.lightLogo}
          onClick={() => {
            publishDps({
              light: !light,
            });
          }}
        />
      </View>
    );
  };

  const renderFunction = () => {
    const uvlist = decodeDisinfect(uvOnOffTime);
    const hasUv = uvlist.some(item => item.status);
    const funcList = [
      {
        title: Strings.getLang('autoClean'),
        tips: Strings.formatValue('autoCleanTips', delayCleanTime),
        code: 'auto_clean',
        type: 'boolean',
        icon: res.autoClean,
        value: autoClean,
        onClick: () => {
          setDoubleCheck({
            show: true,
            title: Strings.getLang('autoClean'),
            tips: Strings.getLang(autoClean ? 'autoCleanTips_on' : 'autoCleanTips_off'),
            onConfirmCallBack: () => {
              publishDps({
                auto_clean: !autoClean,
              });

              if (!autoClean) {
                setCleanTimeShow(true);
              }
            },
          });
        },
      },
      {
        title: Strings.getLang('uvOnOffTime'),
        value: '',
        tips: Strings.getLang(hasUv ? 'uvOnOffTimeTips_on' : 'uvOnOffTimeTips_off'),
        isLink: true,
        icon: res.xd,
        code: 'uv_onoff_time',
        onClick: () => {
          handleJump('sterillizationSchedule');
        },
      },
      {
        title: Strings.getLang('filterReset'),
        value: '',
        tips: Strings.formatValue('filterResetTips', filterDays),
        isLink: true,
        icon: res.replace,
        code: 'filter_reset',
        onClick: () => {
          setDoubleCheck({
            show: true,
            title: Strings.getLang('filterReset'),
            tips: Strings.formatValue('filterResetChangeTips', filterDays),
            onConfirmCallBack: () => {
              publishDps({
                filter_reset: !filterReset,
              });
            },
          });
        },
      },

      {
        title: Strings.getLang('sleepOnOffTime'),
        value: '',
        tips: sleepTime.status
          ? `${getTimeMeasureUtils({
              hour: sleepTime.starthour,
              minute: sleepTime.startminute,
            })}-${
              sleepTime.endhour * 60 + sleepTime.endminute >
              sleepTime.starthour * 60 + sleepTime.startminute
                ? ''
                : Strings.getLang('nextDay')
            }${getTimeMeasureUtils({
              hour: sleepTime.endhour,
              minute: sleepTime.endminute,
            })}`
          : '',
        isLink: true,
        icon: res.disturb,
        code: 'sleep_onoff_time',
        onClick: () => {
          // handleJump('sleepSchedule');
          setSleepOption({
            show: true,
            status: 'list',
          });
        },
      },
      {
        title: Strings.getLang('childLock'),
        value: childLock,
        // tips: Strings.getLang('childLockTips'),
        // isLink: true,
        type: 'boolean',
        icon: res.lock,
        code: 'child_lock',
        onClick: () => {
          childLock
            ? publishDps({
                child_lock: !childLock,
              })
            : setDoubleCheck({
                show: true,
                title: Strings.getLang('childLock'),
                tips: Strings.getLang('childLockTips_on'),
                onConfirmCallBack: () => {
                  publishDps({
                    child_lock: !childLock,
                  });
                },
              });
        },
      },
    ];
    return (
      <View className={styles.functionContainer}>
        {funcList.map(item => (
          <Cell
            key={item.code}
            title={item.title}
            label={item.tips}
            icon={item.icon}
            labelClass={styles.cellLabel}
            titleClass={styles.cellTitle}
            customClass={styles.cellClass}
            isLink={item.isLink}
            onClick={() => {
              if (item.isLink) {
                item.onClick();
              }

              if (item.code === 'auto_clean') {
                // setCleanTimeShow(true);

                if (autoClean) {
                  setCleanTimeShow(true);
                } else {
                  item.onClick();
                }
              }
            }}
          >
            {item.type === 'boolean' ? (
              <Switch
                checked={item.value}
                onChange={() => {
                  item.onClick();
                }}
                stopClickPropagation
              />
            ) : null}
          </Cell>
        ))}
      </View>
    );
  };

  const renderInfo = useMemo(() => {
    return <InfoCom onClick={() => handleJump('curve')} />;
  }, []);

  return (
    <View className={styles.view}>
      <NavBarCustom />
      <ScrollView
        style={{
          height: `calc(${height}px - env(safe-area-inset-bottom) - env(safe-area-inset-top) - 150rpx)`,
        }}
        scrollY
      >
        {renderSchedule()}
        {renderLogo()}
        {renderInfo}
        {renderFunction()}
      </ScrollView>

      <ActionSheet
        show={doubleCheck.show}
        onCancel={() => setDoubleCheck({ ...doubleCheck, show: false })}
        // onConfirm={doubleCheck.onConfirmCallBack}
      >
        <View className={styles.content}>
          <View className={styles.titleText}>{doubleCheck.title}</View>
          <View className={styles.tipsText}>{doubleCheck.tips}</View>
          <View className={styles.buttonGroup}>
            <Button
              className={styles.button}
              onClick={() => setDoubleCheck({ ...doubleCheck, show: false })}
            >
              {Strings.getLang('cancel')}
            </Button>
            <Button
              className={styles.button}
              onClick={() => {
                doubleCheck.onConfirmCallBack();
                setDoubleCheck({ ...doubleCheck, show: false });
              }}
            >
              {Strings.getLang('confirm')}
            </Button>
          </View>
        </View>
      </ActionSheet>

      <ActionSheet
        show={sleepOption.show}
        onCancel={() => setSleepOption({ ...sleepOption, show: false })}
      >
        {sleepOption.status === 'list' ? (
          <View className={styles.content}>
            <View className={styles.editTitleSleep}>
              <Text>{Strings.getLang('sleepOnOffTime')}</Text>
            </View>
            <View>
              <Text className={styles.editTips}>{Strings.getLang('sleepOnOffTimeTips')}</Text>
            </View>
            <View className={styles.setGroup}>
              <Cell
                title={Strings.getLang('sleepOnOffTime')}
                titleStyle={{
                  fontWeight: 700,
                }}
                valueClass={styles.valueText}
                onClick={() => setSleepOption({ status: 'startTime', show: true })}
              >
                <Switch
                  onChange={() => {
                    setSleepTimeConfig({
                      ...sleepTimeConfig,
                      status: sleepTimeConfig.status === 1 ? 0 : 1,
                    });
                  }}
                  checked={sleepTimeConfig.status === 1}
                  stopClickPropagation
                />
              </Cell>
              <Cell
                title={Strings.getLang('sleepStartTime')}
                // value={getTimeMeasureUtils(addTime)}

                value={getTimeMeasureUtils({
                  hour: sleepTimeConfig.starthour,
                  minute: sleepTimeConfig.startminute,
                })}
                titleStyle={{
                  fontWeight: 700,
                }}
                isLink
                customClass={sleepTimeConfig.status !== 1 && styles.cellClass}
                valueClass={styles.valueText}
                onClick={() => {
                  if (sleepTimeConfig.status !== 1) return;
                  setSleepOption({ status: 'startTime', show: true });
                }}
              />
              <Cell
                title={Strings.getLang('sleepEndTime')}
                isLink
                value={getTimeMeasureUtils({
                  hour: sleepTimeConfig.endhour,
                  minute: sleepTimeConfig.endminute,
                })}
                titleStyle={{
                  fontWeight: 700,
                }}
                customClass={sleepTimeConfig.status !== 1 && styles.cellClass}
                valueClass={styles.valueText}
                onClick={() => {
                  if (sleepTimeConfig.status !== 1) return;
                  setSleepOption({ status: 'endTime', show: true });
                }}
              />
            </View>
            <View className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => setSleepOption({ status: 'list', show: false })}
              >
                {Strings.getLang('cancel')}
              </Button>
              <Button
                className={styles.button}
                onClick={() => {
                  if (
                    sleepTimeConfig.starthour * 60 + sleepTimeConfig.startminute ===
                    sleepTimeConfig.endhour * 60 + sleepTimeConfig.endminute
                  ) {
                    showToast({
                      icon: 'error',
                      title: Strings.getLang('sleepStartTimeEndSameTips'),
                    });
                    return;
                  }
                  publishDps({
                    sleep_onoff_time: encodeDisturb(sleepTimeConfig),
                  });
                  setSleepOption({ status: 'list', show: false });
                }}
              >
                {Strings.getLang('confirm')}
              </Button>
            </View>
          </View>
        ) : (
          <View className={styles.content}>
            <View className={styles.editTitle}>
              {Strings.getLang(
                sleepOption.status === 'startTime' ? 'sleepStartTime' : 'sleepEndTime'
              )}
            </View>
            <View className={styles.pickerBox}>
              <View className={styles.timePickerBox}>
                <DateTimePicker
                  type="time"
                  value="12:00"
                  showToolbar={false}
                  onInput={v => {
                    const hour = (v.detail as string).split(':')[0];
                    const minute = (v.detail as string).split(':')[1];
                    // sleepOption.status === 'startTime'
                    //   ?

                    sleepTimeConfigRef.current = {
                      ...sleepTimeConfigRef.current,
                      [sleepOption.status === 'startTime' ? 'starthour' : 'endhour']: Number(hour),
                      [sleepOption.status === 'startTime' ? 'startminute' : 'endminute']:
                        Number(minute),
                    };
                  }}
                  locale={{
                    hour: Strings.getLang('hour'),
                    minute: Strings.getLang('minute'),
                  }}
                />
              </View>
            </View>
            <View className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => setSleepOption({ status: 'list', show: false })}
              >
                {Strings.getLang('cancel')}
              </Button>
              <Button
                className={styles.button}
                onClick={() => {
                  setSleepTimeConfig({
                    ...sleepTimeConfigRef.current,
                  });

                  setSleepOption({ status: 'list', show: true });
                }}
              >
                {Strings.getLang('confirm')}
              </Button>
            </View>
          </View>
        )}
      </ActionSheet>

      <ActionSheet show={cleanTimeShow} onCancel={() => setCleanTimeShow(false)}>
        <View className={styles.content}>
          <View className={styles.editTitle}>{Strings.getLang('cleanDelayTimeTitle')}</View>
          <View className={styles.pickerBox}>
            <View className={styles.timePickerBox}>
              <Picker
                columns={columns}
                onChange={event => {
                  const { picker, value } = event.detail;
                  if (+value[0] === 10) {
                    picker.setColumnValues(1, zeroCol);
                  } else {
                    picker.setColumnValues(1, columns[1].values);
                  }
                  delayCleanTimeRef.current = +value[0] * 60 + +value[1];
                }}
              />
            </View>
          </View>
          <View className={styles.buttonGroup}>
            <Button className={styles.button} onClick={() => setCleanTimeShow(false)}>
              {Strings.getLang('cancel')}
            </Button>
            <Button
              className={styles.button}
              onClick={() => {
                publishDps({
                  delay_clean_time: delayCleanTimeRef.current,
                });
                setCleanTimeShow(false);
              }}
            >
              {Strings.getLang('confirm')}
            </Button>
          </View>
        </View>
      </ActionSheet>

      <BotBar doubleCheck={setDoubleCheck} />
    </View>
  );
}

export default Home;
